//
//  ClassDetailViewController.m
//  FingerUniversity
//
//  Created by vantle on 16/3/15.
//  Copyright © 2016年 vantle. All rights reserved.
//

#import "ClassDetailViewController.h"
#import "ClassDetailCell.h"
#import "AFNetworking.h"
#import "ClassDetailViewController.h"
#import "AFNetworking.h"
#import "File.h"
#import "MobClick.h"
#import "playViewController.h"

#define ScreenHeight [UIScreen mainScreen].bounds.size.height
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
@interface ClassDetailViewController ()

@end
@implementation ClassDetailViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [MobClick beginLogPageView:@"ClassDetailViewController"];//("PageOne"为页面名称，可自定义)
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [MobClick endLogPageView:@"ClassDetailViewController"];
}
-(void)viewDidLoad
{
    self.view.backgroundColor=[UIColor whiteColor];
    
    UIImageView*bg=[[UIImageView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64)];
    bg.image=[UIImage imageNamed:@"bg"];
    [self.view addSubview:bg];
    
    UIImageView*barImage=[[UIImageView alloc]initWithFrame:CGRectMake(0, 20, ScreenWidth, 44)];
    barImage.userInteractionEnabled=YES;
    barImage.backgroundColor=[UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1];
    [self.view addSubview:barImage];
    
    UIButton*backButton=[UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame=CGRectMake(0, 0, 100, 44);
    [backButton addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [barImage addSubview:backButton];
    
    UIImageView*backImage=[[UIImageView alloc]initWithFrame:CGRectMake(5, 12, 5, 20)];
    backImage.image=[UIImage imageNamed:@"back_arrowleft"];
    [barImage addSubview:backImage];
    
    UIImageView*logoImage=[[UIImageView alloc]initWithFrame:CGRectMake(backImage.frame.origin.x+backImage.frame.size.width+3, 6, 32, 32)];
    logoImage.layer.cornerRadius=3;
    logoImage.clipsToBounds=YES;
    logoImage.image=[UIImage imageNamed:@"app-logo-80"];
    [barImage addSubview:logoImage];
    
   UILabel* noticeLabel=[[UILabel alloc]initWithFrame:CGRectMake(logoImage.frame.origin.x+logoImage.frame.size.width+5, 10, 100, 25)];
    noticeLabel.text=@"课程详情";
    [barImage addSubview:noticeLabel];
    
    _cellTitleArray=@[@"主讲老师:",@"文件名称:",@"文件类型:",@"时长:",@"文件大小:",@"上传时间:"];
    
    _listArray=[[NSMutableArray alloc]initWithCapacity:0];
    
    [self getClassInfo];
    
}
-(void)setContent
{
    _tabelView=[[UITableView alloc]initWithFrame:CGRectMake(10, 74, ScreenWidth-20, ScreenHeight-74)];
    _tabelView.dataSource=self;
    _tabelView.delegate=self;
    _tabelView.separatorColor=[UIColor whiteColor];
    _tabelView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:_tabelView];
    if (ScreenWidth==320) {
        _tabelView.scrollEnabled=YES;
    }
    else
    {
        _tabelView.scrollEnabled=NO;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 8;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ClassDetailCell*cell=[[ClassDetailCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    
    if (indexPath.row==0) {
        UILabel*title=[[UILabel alloc]init];
        title.center=CGPointMake(ScreenWidth/2, 23);
        title.bounds=CGRectMake(0, 0, 200, 30);
        title.font=[UIFont systemFontOfSize:22];
        title.textAlignment=1;
        title.text=self.name;
        [cell.contentView addSubview:title];
        
        if (self.type==3||self.type==4) {
            UIButton*playButton=[UIButton buttonWithType:UIButtonTypeCustom];
            playButton.center=CGPointMake(ScreenWidth/2, title.center.y+60);
            playButton.bounds=CGRectMake(0, 0, 200, 60);
            [playButton setBackgroundImage:[UIImage imageNamed:@"矩形-1"]forState:UIControlStateNormal];
            [playButton setTitle:@"点击播放" forState:UIControlStateNormal];
            [playButton addTarget:self action:@selector(playButtonClick) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:playButton];
        }
        else
        {
            UIButton*playButton=[UIButton buttonWithType:UIButtonTypeCustom];
            playButton.center=CGPointMake(ScreenWidth/2, title.center.y+60);
            playButton.bounds=CGRectMake(0, 0, 200, 60);
            [playButton setBackgroundImage:[UIImage imageNamed:@"矩形-1"]forState:UIControlStateNormal];
            [playButton setTitle:@"点击预览" forState:UIControlStateNormal];
            [playButton addTarget:self action:@selector(playButtonClick) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:playButton];
        }
    }
    
    else if(indexPath.row==7)
    {
        cell.titleLabel.text=@"文件简介:";
        UILabel*textLable=[[UILabel alloc]initWithFrame:CGRectMake(cell.titleLabel.frame.origin.x, cell.titleLabel.frame.origin.y+cell.titleLabel.frame.size.height, ScreenWidth-140, 25)];
        textLable.numberOfLines=0;
        textLable.text=self.content;
        [cell.contentView addSubview:textLable];
    }
    else
    {
        cell.titleLabel.text=_cellTitleArray[indexPath.row-1];
        
        CGSize detailSize = [cell.titleLabel.text sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(MAXFLOAT, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
        
        
        UILabel*contentLabel=[[UILabel alloc]init];
        contentLabel.frame=CGRectMake(cell.titleLabel.frame.origin.x+detailSize.width+5, cell.titleLabel.frame.origin.y, ScreenWidth-130, 25);
        [cell.contentView addSubview:contentLabel];
        if (indexPath.row==1) {
            if (self.speaker.length!=0) {
                contentLabel.text=self.speaker;
            }
            else
            {
                contentLabel.text=@"未知";
            }
        }
       else if (indexPath.row==2) {
           if (self.fileName.length!=0) {
               contentLabel.text=self.fileName;
           }
           else
           {
               contentLabel.text=@"未知";
           }
        }
       else if (indexPath.row==3) {
           
               if (self.type==1) {
                   contentLabel.text=@"文本";
               }
               else  if (self.type==2) {
                   contentLabel.text=@"图片";
               }
               else  if (self.type==3) {
                   contentLabel.text=@"视频";
               }
               else if (self.type==4)
               {
                   contentLabel.text=@"音频";
               }
               else if (self.type==5)
               {
                   contentLabel.text=@"文档";
               }
               else
               {
                   contentLabel.text=@"未知类型";
               }
       }
       else if (indexPath.row==4) {
           if (self.duration.length!=0) {
               contentLabel.text=self.duration;
           }
           else
           {
               contentLabel.text=@"未知";
           }
       }
       else if (indexPath.row==5) {
           if (self.fileSize.length!=0) {
               contentLabel.text=self.fileSize;
           }
           else
           {
               contentLabel.text=@"未知";
           }
       }
       else  {
           
           if (self.createTime.length!=0) {
               contentLabel.text=self.createTime;
           }
           else
           {
               contentLabel.text=@"未知";
           }
       }
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.backgroundColor=[UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:0.5];
    return cell;
}
-(void)getClassInfo
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString*userId=[userDefaults objectForKey:@"userId"];
    NSLog(@"======%@",userId);
    NSString*flag=[userDefaults objectForKey:@"flag"];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes =[manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
    
    NSDictionary*params=@{@"userId":userId,@"flag":flag,@"courseId":self.QuId};
    
    [manager POST:@"http://120.76.79.85:9080/mzdx/service/courseDetail.action" parameters:params success: ^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSData*responseData=responseObject;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData
                                                            options:NSJSONReadingMutableContainers
                                                              error:nil];
        NSLog(@"🐶＝＝＝＝＝＝%@",dic);
        NSString*rType=[dic objectForKey:@"rType"];
        if ([rType isEqualToString:@"1"]) {
            self.name=[dic objectForKey:@"name"];
            self.speaker=[dic objectForKey:@"speaker"];
            self.fileName=[dic objectForKey:@"fileName"];
            self.type=[[dic objectForKey:@"type"] integerValue];
            self.duration=[dic objectForKey:@"duration"];
            self.fileSize=[dic objectForKey:@"fileSize"];
            self.createTime=[dic objectForKey:@"createTime"];
            self.content=[dic objectForKey:@"content"];
            self.fileUrl=[dic objectForKey:@"fileUrl"];
        }
        NSLog(@"------------%d",self.type);
        if (dic!=nil) {
            [self setContent];
        }
        
    } failure: ^(AFHTTPRequestOperation * operation, NSError *error) {
        NSLog(@"%@", error);
    }];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        return 130;
    }
    else if(indexPath.row==7)
    {
        return 100;
    }
    else
    {
        return 44;
    }
}
-(void)playButtonClick
{
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)self.fileUrl,
                                                              (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
                                                              NULL,
                                                              kCFStringEncodingUTF8));
    if (self.type==3||self.type==4) {
        [self openmovie:encodedString];
    }
    else
    {
        playViewController*playVC=[[playViewController alloc]init];
        playVC.url=self.fileUrl;
        playVC.type=self.type;
        [self.navigationController pushViewController:playVC animated:YES];
    }
    
}
-(void)openmovie:(NSString*)url
{
    _movie = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:url]];

    [_movie.moviePlayer prepareToPlay];
    [self.view addSubview:_movie.view];
    [_movie.moviePlayer setControlStyle:MPMovieControlStyleFullscreen];
    if (self.type==4) {
        UIImageView*bg=[[UIImageView alloc]initWithFrame:self.view.frame];
        bg.image=[UIImage imageNamed:@"bg"];
        [_movie.moviePlayer.backgroundView addSubview:bg];
    }
    [_movie.view setFrame:self.view.bounds];
    [[NSNotificationCenter defaultCenter]addObserver:self

                                           selector:@selector(movieFinishedCallback:)

                                               name:MPMoviePlayerPlaybackDidFinishNotification

                                             object:_movie.moviePlayer];

}
-(void)movieFinishedCallback:(NSNotification*)notify{

    // 视频播放完或者在presentMoviePlayerViewControllerAnimated下的Done按钮被点击响应的通知。

    MPMoviePlayerController* theMovie = [notify object];

    [[NSNotificationCenter defaultCenter]removeObserver:self

                                                  name:MPMoviePlayerPlaybackDidFinishNotification

                                                object:theMovie];

//    [self dismissMoviePlayerViewControllerAnimated];

    [_movie.view removeFromSuperview];

}

-(void)backButtonClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewDidLayoutSubviews
{
    if ([_tabelView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_tabelView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([_tabelView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tabelView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationLandscapeLeft;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}
@end
